package register;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import com.avos.avoscloud.AVException;
import com.avos.avoscloud.AVFile;
import com.avos.avoscloud.AVObject;
import com.avos.avoscloud.AVQuery;
import com.avos.avoscloud.AVUser;
import com.avos.avoscloud.FindCallback;
import com.avos.avoscloud.LogInCallback;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import co.yeye.test.MainActivity;
import co.yeye.test.R;

/**
 * Created by yeye on 15/2/17.
 */
public class Login extends Activity{

    ImageLoader imageLoader;
    DisplayImageOptions options;

    ImageView img;
    EditText user,password;
    Button tittle,btn_confirm;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login);

        tittle = (Button) findViewById(R.id.tittle);
        user = (EditText) findViewById(R.id.user);
        password = (EditText) findViewById(R.id.pwk);
        img = (ImageView) findViewById(R.id.login_img);
        btn_confirm = (Button) findViewById(R.id.btn_login);

        tittle.setVisibility(View.GONE);

        imageLoader = MainActivity.getInstance().getImageLoader();
        options = MainActivity.getInstance().getOptionCache();

        user.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i2, int i3) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i2, int i3) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                /*
                if(user.getText().toString().length()>12){
                    setTittle("学号太长咯", Color.parseColor("#f5a85d"), 3000,false);
                    return;
                }
                */
                // 查询用户名
                AVQuery<AVObject> query_username = new AVQuery<AVObject>("_User");
                query_username.whereEqualTo("username", user.getText().toString());
                // 查询电话号码
                AVQuery<AVObject> query_phone = new AVQuery<AVObject>("_User");
                query_phone.whereEqualTo("mobilePhoneNumber", user.getText().toString());
                // 构建“或”的搜索
                List<AVQuery<AVObject>> queries = new ArrayList<AVQuery<AVObject>>();
                queries.add(query_username);
                queries.add(query_phone);
                // 搜索组
                AVQuery<AVObject> mainQuery = AVQuery.or(queries);
                mainQuery.findInBackground(new FindCallback<AVObject>() {
                    @Override
                    public void done(List<AVObject> avObjects, AVException e) {
                        if(e==null){
                            if(avObjects.size()<=0){
                                img.setImageDrawable(getResources().getDrawable(R.drawable.user_blank_null));
                                //return;
                                /*
                                //img.setImageDrawable(getResources().getDrawable(R.drawable.user_blank_null));
                                // 尝试用电话查询
                                AVQuery<AVObject> queryPhone = new AVQuery<AVObject>("_User");
                                queryPhone.whereEqualTo("mobilePhoneNumber",user.getText().toString());
                                queryPhone.findInBackground(new FindCallback<AVObject>() {
                                    @Override
                                    public void done(List<AVObject> avObjects, AVException e) {
                                        if(e==null){
                                            if(avObjects.size()<=0){
                                                img.setImageDrawable(getResources().getDrawable(R.drawable.user_blank_null));
                                                return;
                                            }
                                            else{
                                                AVObject avObject = avObjects.get(0);
                                                AVFile avFile = avObject.getAVFile("user_img");
                                                String uri = avFile.getUrl();
                                                imageLoader.displayImage(uri,img,options, null);
                                            }
                                        }
                                    }
                                });
                                */
                                //return;
                            }
                            else {
                                AVObject avObject = avObjects.get(0);
                                AVFile avFile = avObject.getAVFile("user_img");
                                String uri = avFile.getUrl();
                                imageLoader.displayImage(uri, img, options, null);
                            }
                        }
                    }
                });
            }
        });

        btn_confirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // 使用AVUser
                AVUser avUser = new AVUser();
                // 使用用户名登陆
                avUser.logInInBackground(user.getText().toString(),password.getText().toString(),new LogInCallback<AVUser>() {
                    @Override
                    public void done(AVUser avUser, AVException e) {
                        if(e==null){
                            loginSuccess(avUser);
                        }
                        else{
                            // 尝试用电话登陆
                            avUser.loginByMobilePhoneNumberInBackground(user.getText().toString(),password.getText().toString(),
                                    new LogInCallback<AVUser>() {
                                        @Override
                                        public void done(AVUser avUser, AVException e) {
                                            if(e==null){
                                                loginSuccess(avUser);
                                            }
                                            else{
                                                setTittle("账号或密码错误", Color.parseColor("#f5a85d"), 3000,false);
                                            }
                                        }
                                    });
                        }
                    }
                });

                /*
                // 验证学号和密码
                AVQuery<AVObject> query = new AVQuery<AVObject>("UserDB");
                query.whereEqualTo("code", user.getText().toString());
                query.whereEqualTo("password", password.getText().toString());
                query.findInBackground(new FindCallback<AVObject>() {
                    @Override
                    public void done(List<AVObject> avObjects, AVException e) {
                        if(e==null){
                            if(avObjects.size()<=0)
                                setTittle("学号或密码错误", Color.parseColor("#f5a85d"), 3000,false);
                            else{
                                btn_confirm.setText("正在返回");
                                btn_confirm.setClickable(false);
                                setTittle("登录成功", Color.parseColor("#f5a85d"), 1000, true);

                                AVObject avObject = avObjects.get(0);
                                AVFile avFile = avObject.getAVFile("user_img");
                                String uri = avFile.getUrl();
                                String username = avObjects.get(0).getString("username");
                                String name = avObjects.get(0).getString("name");
                                String user_code = user.getText().toString();
                                MainActivity.getInstance().setSlideInfo(uri,username,user_code,name);

                                // 保存文件路径
                                SharedPreferences sharedPreferences = getSharedPreferences("MyOpto", Context.MODE_PRIVATE);
                                SharedPreferences.Editor editor;
                                editor = sharedPreferences.edit();
                                //String user_code = code.getText().toString();
                                editor.putBoolean("isLogin",true);
                                editor.putString("name",name);
                                editor.putString("user_name",username);
                                editor.putString("user_code",user_code);
                                editor.putString(user_code+"_img_uri",uri);
                                editor.commit();
                            }
                        }
                    }
                });
                */
            }
        });
    }

    /**
     * 登陆成功
     */
    private void loginSuccess(AVUser avUser){
        AVFile avFile = avUser.getAVFile("user_img");
        String uri = avFile.getUrl();
        String username = avUser.getString("username");
        String name = avUser.getString("name");
        String user_code = avUser.getString("user_ID");
        MainActivity.getInstance().setSlideInfo(uri,username,user_code,name);

        // 保存文件路径
        SharedPreferences sharedPreferences = getSharedPreferences("MyOpto", Context.MODE_PRIVATE);
        SharedPreferences.Editor editor;
        editor = sharedPreferences.edit();
        //String user_code = code.getText().toString();
        editor.putBoolean("isLogin",true);
        editor.putString("name",name);
        editor.putString("pwk",password.getText().toString());
        editor.putString("user_name",username);
        editor.putString("user_code",user_code);
        editor.putString(user_code+"_img_uri",uri);
        editor.commit();

        Toast.makeText(getBaseContext(),"登陆成功",Toast.LENGTH_SHORT).show();
        finish();
    }

    /**
     * 配置顶部的按钮
     */
    private void setTittle( String text , int color , int time , final boolean isGone ){
        tittle.setText(text);
        tittle.setBackgroundColor(color);
        tittle.setVisibility(View.VISIBLE);

        if(time!=0) {
            Handler handler = new Handler();
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    tittle.setVisibility(View.GONE);
                    if (isGone)
                        finish();
                }
            }, time);
        }

    }
}
